package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.UserLoginDto;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginVo;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-22
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private WechatService wechatService;

    private List<String> nickNameList = Arrays.asList("好柿开花", "大吉大利", "今晚吃鸡", "三羊开泰");

    @Autowired
    private TokenService tokenService;

    /**
     * 微信小程序登录接口
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginDto dto) {
        //1. 获取微信唯一身份标识openId
        String openId = wechatService.getOpenId(dto.getCode());

        //2. 根据openId查询用户
        FamilyMember member = this.lambdaQuery().eq(FamilyMember::getOpenId, openId).one();

        //3. 如果用户不存在则新增用户（自动注册）
        if(member==null) {
            Collections.shuffle(nickNameList);//打乱集合中元素的顺序

            //生成随机昵称
            String nickName  = nickNameList.get(0) + RandomStringUtils.randomNumeric(4);

            member = FamilyMember.builder()
                    .openId(openId) //唯一标识
                    .name(nickName)//昵称
                    .build();
            this.save(member);
        }

        //4. 如果手机号不存在则获取微信绑定的手机号
        if(StrUtil.isBlank(member.getPhone())) {
            String phoneNum = wechatService.getPhoneNum(dto.getPhoneCode());

            //5. 更新手机号到用户表
//            FamilyMember memberUpdate = FamilyMember.builder()
//                    .id(member.getId()) //更新条件
//                    .phone(phoneNum)//更新字段对应的值
//                    .build();
//            this.updateById(memberUpdate);

            if(StrUtil.isNotBlank(phoneNum)) {
                this.lambdaUpdate()
                        .eq(FamilyMember::getId, member.getId()) //更新条件
                        .set(FamilyMember::getPhone, phoneNum)//更新字段对应的值
                        .update();
            }
        }

        //6. 基于userId和昵称生成Token令牌
        String token = tokenService.createToken(
                Map.of(
                        "userId", member.getId(),
                        "nickName", member.getName()
        ));

        //7. 封装响应结果对象
        return LoginVo.builder().nickName(member.getName()).token(token).build();
    }
}
